﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;

namespace GdHotel.Data.Helpers
{
    public class GraphicsHelper
    {
        public static void ResizePhoto(string filePath, Size size, HttpServerUtilityBase server)
        {
            var absPath = server.MapPath(filePath);
            var imageToResize = new Bitmap(absPath);

            if (imageToResize.Size.Equals(size))
            {
                imageToResize.Dispose();
                return;
            }

            var kw = imageToResize.Width / (float)size.Width;
            var kh = imageToResize.Height / (float)size.Height;
            var k = Math.Min(kw, kh);
            int croppedWidth = (int)(size.Width * k);
            int croppedHeight = (int)(size.Height * k);

            using (var resizedImage = new Bitmap(size.Width, size.Height))
            {
                using (var gfx = Graphics.FromImage(resizedImage))
                {
                    var shiftedLocation = new Point((imageToResize.Width - croppedWidth) / 2, (imageToResize.Height - croppedHeight) / 2);
                    var sourceRectangle = new Rectangle(shiftedLocation, new Size(croppedWidth, croppedHeight));
                    var destinationRectangle = new Rectangle(Point.Empty, size);
                    gfx.DrawImage(imageToResize, destinationRectangle, sourceRectangle, GraphicsUnit.Pixel);

                    imageToResize.Dispose();
                    resizedImage.Save(absPath);
                }
            }
        }

        public static string SaveAndResizePicture(HttpPostedFileBase file, Size size, HttpServerUtilityBase server, String directoryRelativePath)
        {
            if (file != null)
            {
                string filePath = file.SavePhoto(directoryRelativePath, server);
                GraphicsHelper.ResizePhoto(filePath, size, server);
                return filePath;
            }
            return null;
        }

    }
}
